/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package softwarehouse;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.util.HashMap;

/**
 *
 * @author matt
 */
public class SoftwareHouse {

    private HashMap<String, String> users;
    private HashMap<String, Integer> components;
    private int passwordEnd;
    private String[] comp;
    private String privateKey;
    private String output;
    private String input;
    private String artifacts;
    private String username;
    private HashMap<Object, String> keys;
    private String company;

    public SoftwareHouse(String company) throws IOException, FileNotFoundException, ClassNotFoundException {
        passwordEnd = 0;
        keys = new HashMap<Object, String>();
        users = new HashMap<String, String>();
        components = new HashMap<String, Integer>();
        users.put("matt", "brightman");
        users.put("username", "password");
        components.put("matt-Hello", 10);
        components.put("matt-World", 10);
        File file = new File("");
        String currentDir = file.getAbsolutePath();
        currentDir = currentDir + "/";

        privateKey = currentDir + "key/" + "mattprk";
        output = currentDir + "output/";
        input = currentDir + "input/";
        artifacts = currentDir + "example/artifacts/";
        this.company = company;
		String valid = check();
        if (valid.equals("")) {
            send();
        }
    }

    public Object toObject(byte[] bytes) {
        Object obj = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            obj = ois.readObject();
        } catch (IOException ex) {
            //TODO: Handle the exception
        } catch (ClassNotFoundException ex) {
            //TODO: Handle the exception
        }
        return obj;
    }

    public boolean checkSig() throws FileNotFoundException, IOException, ClassNotFoundException {
        String sig = input + company + ".lnk.K";
        FileInputStream keyfis = new FileInputStream(sig);
        byte[] encKey = new byte[keyfis.available()];
        keyfis.read(encKey);
        keyfis.close();

        Object key = toObject(encKey);//= deserialize(encKey);
        String user = keys.get(key);
        if (user == null) {
            keys.put(key, username);
            System.out.println("&&&&&1");
            return true;
        } else {
            keys.put(key, username);
            System.out.println(username);
             System.out.println(user);
            return false;
        }
    }

    public String check() throws IOException, FileNotFoundException, ClassNotFoundException {

        String errors = "";
        boolean c = checkLicence(input + company + ".lnk.EN", input + company + ".lnk.K", input + company + ".lnk.Sig", output + "LIC");

        if (c) {
            boolean result = VerifyID(output + "LIC");
            System.out.println("Licence valid? " + result);
            if (result) {

                GenerateProduct p = new GenerateProduct(comp, output, artifacts);


                return "";
            } else {
                errors = errors + "- The username or password may be incorrect. Or you do not have acces to the requested componets\n ";
            }
        } else {
            errors = errors + "- The supplied licence is not legitiment. It may have been altered during transit\n";
        }
        return errors;
    }

    private boolean checkLicence(String file, String SigKey, String SigFile, String outputFile) throws IOException {

        De de = new De(privateKey, file);
        String text = de.decrypt();
        FileWriter fstream = new FileWriter(outputFile);
        BufferedWriter out = new BufferedWriter(fstream);
        out.write(text.substring(0, text.length() - 1));
        //Close the output stream
        out.close();
        System.out.println(text);
        //String p = text.substring(0, text.length()-1);
        VerSig v = new VerSig();
        return v.verify(SigKey, SigFile, outputFile);

    }

    private String getText(String file) throws FileNotFoundException, IOException {
        FileInputStream fstream = new FileInputStream(file);
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        int count = 0;
        //Read File Line By Line
        String line = null;
        while ((strLine = br.readLine()) != null && count == 0) {
            count++;// Print the content on the console
            line = strLine;
        }
        //Close the input stream
        in.close();
        return line;
    }

    private String getUsername(String line) {
        return line.substring(0, line.indexOf(":"));
    }

    private String getPassword(String line) {
        int start = line.indexOf(":");
        int finish = line.indexOf(":", line.indexOf(":") + 1);
        passwordEnd = finish;
        return line.substring(start, finish).replaceFirst(":", "");
    }

    private String[] getComponents(String line) {

        String c = line.substring(passwordEnd + 1, line.indexOf(":", passwordEnd + 2));
        int count = 0;
        for (int i = 0; i < c.length(); i++) {
            if (c.charAt(i) == ',') {
                count++;
            }
        }
        c = c + ",";
        count++;
        String com[] = new String[count];
        int start = 0;
        int finish = c.indexOf(",");
        for (int j = 0; j < com.length; j++) {
            if (j != 0) {
                com[j] = c.substring(start, finish).replaceAll(",", "");
            } else {
                com[j] = c.substring(start, finish);
            }
            start = finish;
            finish = c.indexOf(",", start + 1);

        }
        return com;
    }

    public boolean VerifyID(String file) throws FileNotFoundException, IOException, ClassNotFoundException {
        String line = getText(file);
        username = getUsername(line);
        String password = getPassword(line);
        if (!checkSig()) {
            System.out.println("*********************");
            return false;
        }
        String pass = users.get(username);
        if (pass == null) {
            return false;
        }
        if (!pass.equals(password)) {
            return false;
        }
        String c[] = getComponents(line);
        for (int j = 0; j < c.length; j++) {
            String comp = username + "-" + c[j];

            if (!components.containsKey(comp)) {
                return false;
            }
            int numLeft = components.get(comp);

            if (numLeft <= 0) {
                return false;
            }


        }
        for (int j = 0; j < c.length; j++) {
            String key = username + "-" + c[j];
            int numLeft = components.get(key);
            components.put(key, numLeft--);
        }
        comp = c;
        return true;
    }

    public void send() {
        JavaRunCommand c = new JavaRunCommand();
        File file = new File("");
        String currentDir = file.getAbsolutePath();
        currentDir = currentDir.replaceAll("SoftwareHouse", "LinkBroker/tmp/in/");
        // System.out.println(currentDir);
        c.run("cp " + output + "SH " + currentDir);
    }

    
}
